﻿using ArcLightProtector.Controls;
using IoTClient.Clients.Modbus;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;

namespace ArcLightProtector
{
    public partial class Form1 : Form
    {
        private int _cycleTime;
        private ModbusRtuClient _client;

        private byte _slaveId = 1;


        private List<BaseController> _protectorControllers = new List<BaseController>();
        private BaseController _curController;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitData();
            //InitUI();
            panel1.Enabled = false;
            panel1.Controls.Clear();


            cboType.SelectedIndex = 0;

        }

        private void InitData()
        {
            var portNames = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(portNames);

            _protectorControllers.Add(new Protector1Controller() { Dock = DockStyle.Fill });
            _protectorControllers.Add(new Protector2Controller() { Dock = DockStyle.Fill });
            _protectorControllers.Add(new Protector3Controller() { Dock = DockStyle.Fill });

            foreach (var item in _protectorControllers)
            {
                cboType.Items.Add(item.ProtectorName);
            }
        }

        private void BtnStart_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "开始")
            {
                var portName = comboBox1.Text;
                var baudRate = comboBox2.Text;
                if (string.IsNullOrEmpty(portName))
                {
                    MessageBox.Show("请选择串口");
                    return;
                }
                if (string.IsNullOrEmpty(baudRate))
                {
                    MessageBox.Show("请选择波特率");
                    return;
                }

                if (!byte.TryParse(txtSlaveId.Text, out var slaveId))
                {
                    MessageBox.Show("站位号必须在1-254");
                    return;
                }

                if (_curController == null)
                {
                    MessageBox.Show("装置设备不能为空");
                    return;
                }

                _slaveId = slaveId;
                //_client.Setup(new TouchSocketConfig().SetSerialPortOption(new SerialPortOption
                //{
                //    PortName = portName,
                //    BaudRate = int.Parse(baudRate)
                //}));

                _client = new ModbusRtuClient(portName, int.Parse(baudRate), 8, StopBits.One, Parity.None);
                try
                {
                    _client.Open();
                    comboBox1.Enabled = false;
                    comboBox2.Enabled = false;
                    cboType.Enabled = false;
                    txtSlaveId.Enabled = false;
                    panel1.Enabled = true;
                    panel2.Enabled = true;

                    btnStart.Text = "停止";
                    //foreach (var control in _dic.Values)
                    //{
                    //    control.SetModbusClient(_slaveId, _client);
                    //}
                    //_tokenSource = new CancellationTokenSource();
                    //Task.Factory.StartNew(CollectData, TaskCreationOptions.LongRunning);
                    _curController.SetCycleTime(_cycleTime);
                    _curController.SetModbusClient(_client);
                    _curController.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                cboType.Enabled = true;
                txtSlaveId.Enabled = true;
                panel1.Enabled = false;
                panel2.Enabled = false;
                _curController.Stop();
                btnStart.Text = "开始";
                //_tokenSource.Cancel();
            }
        }

        private void BtnSet_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtCycleTime.Text, out var i))
            {
                _cycleTime = i;
                _curController?.SetCycleTime(_cycleTime);
            }
        }

        private double CompuateValue(SensorPointData data, uint value)
        {
            if (data.Operator == "/") return value * 1.0 / data.OperationValue.Value;
            else if (data.Operator == "*") return value * 1.0 * data.OperationValue.Value;
            return 0;
        }

        private void cboType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboType.SelectedIndex == 0 || cboType.SelectedIndex == 2) //导轨弧光保护
            {
                this.WindowState = FormWindowState.Normal;
                this.Width = 1131;
                this.Height = 604;
            }
            else if (cboType.SelectedIndex == 1) //母线弧光
            {
                this.WindowState = FormWindowState.Normal;
                this.Width = 1200;
                this.Height = 800;
            }
            _curController = _protectorControllers[cboType.SelectedIndex];
            panel1.Controls.Clear();
            panel1.Controls.Add(_curController);
        }
    }
}
